<template>
  <div class="serverConfig">
    <div class="page-head">
      <div class="page-bread">
        <div class="bread-prev" @click="back(-2)">数据模板</div>
        <div class="bread-divider">/</div>
        <div class="bread-prev" @click="back(-1)">上传服务器配置</div>
        <div class="bread-divider">/</div>
        <div class="bread-now">参数配置</div>
      </div>
      <div class="bread-info">
        <span>业务模板名称：{{$route.query.name}}</span>  
        <span class="ml15"> CNC类型：{{$route.query.cnc_name}}</span>
      </div>
      <div class="page-tool">
        <search-input placeholder="参数名称搜索" @search="searchChange" />
        <div
          class="tool-btn"
          @click="exportData"
        >
          模板下载
        </div>
        <div
          class="tool-btn"
        >
          <input
            type="file"
            class="file-input"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            ref="prepare_import"
            @change="batchExcel($event, 'prepare_import')"
          >
          批量导入
        </div>
        <div class="tool-btn" @click="open('add')">新增参数</div>
      </div>
    </div>
    <div class="page-body">
      <div class="table_data">
        <el-table :data="tableData" stripe border :fit="true" :height="$tableHeight">
          <el-table-column
            prop="name"
            :show-overflow-tooltip="true"
            label="参数名称"
          >
          </el-table-column>

          <el-table-column
            label="参数类型"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="{ row }">
              <div>
                {{ parmeterTypelist.find((s) => s.k == row.parmeter_type).v }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="pwe"
            label="参数值">
          </el-table-column>

          <el-table-column label="操作" align="center" width="120">
            <template slot-scope="{ row }">
              <div class="operation-col">
                <div class="txt-btn ope-btn" @click="open('update', row)">
                  <el-tooltip
                    effect="dark"
                    content="修改"
                    placement="top-start"
                  >
                    <img src="~assets/img/edit.png" alt="" />
                  </el-tooltip>
                </div>
                <div class="txt-btn" @click="doDelete(row)">
                  <el-tooltip
                    effect="dark"
                    content="删除"
                    placement="top-start"
                  >
                    <img src="~assets/img/delete.png" alt="" />
                  </el-tooltip>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-footer">
        <pagina-tion
          class="page-pager"
          v-show="total >= 0"
          :background="true"
          :total="total"
          :offset.sync="offset"
          :limit.sync="limit"
          @pagination="getChangePage"
          @sizeChange="getSizePage"
        />
      </div>
    </div>

    <!-- 新增参数弹窗 -->
    <el-dialog
      :visible.sync="model.visible"
      width="370px"
      :title="model.type === 'add' ? '新增参数' : '修改参数'"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="dialog-body">
        <el-form
          ref="form"
          :model="form"
          label-width="110px"
          label-position="left"
        >
          <el-form-item label="参数名称" class="required">
            <el-input
              name="paramsName"
              placeholder="请输入参数名称"
              v-model="form.name"
              v-validate="'required'"
            />
            <div v-show="errors.has('paramsName')" class="el-form-item__error">
              {{ errors.first("paramsName") }}
            </div>
          </el-form-item>
          <el-form-item label="参数类型" label-position="left" class="required">
            <el-select
              v-model="form.parmeter_type"
              placeholder="请选择参数类型"
              name="parmeter_type"
              v-validate="'required'"
              @change="parmeterTypeChange"
            >
              <el-option
                v-for="item in parmeterTypelist"
                :key="item.k"
                :label="item.v"
                :value="item.k"
              >
              </el-option>
            </el-select>
            <div v-show="errors.has('parmeter_type')" class="el-form-item__error">
              {{ errors.first("parmeter_type") }}
            </div>
          </el-form-item>

          <el-form-item label="参数值" class="required">
            <el-select
              v-model="form.pwe"
              name="pwe"
              v-validate="'required'"
              placeholder="请选择参数值"
              filterable
            >
              <el-option
                v-for="item in pweList"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
            <div v-show="errors.has('pwe')" class="el-form-item__error">
              {{ errors.first("pwe") }}
            </div>
          </el-form-item>

        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 删除弹窗 -->
    <el-dialog
      :visible.sync="visibility"
      width="430px"
      height="100px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content comfirm-body">
        <img class="comfirm-ico" src="~assets/img/warning.png" />
        <div class="comfirm-txt">
          <div>确定删除该条数据？</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="visibility = false">取 消</el-button>
        <el-button type="primary" @click="asyncDelete">确 定</el-button>
      </span>
    </el-dialog>

    <result-dialog
      v-if="resultVisable"
      :parmeterTypelist="parmeterTypelist"
      :unableList="unableList"
      :ableList="ableList"
      @cancel="resultCancel"
      @sure="resultSure"
    />
  </div>
</template>


<script>
import * as api from "@/api";
import { limit, smallLimit } from "@/consts/consts";
import { parameterKey } from "@/consts/formKey";
import { readExcel } from "@/utils/excel";
import { downLoadFile } from "@/utils/tool";
import searchInput from "@/components/libs/searchInput";
import paginaTion from "@/components/libs/paginaTion";

export default {
  components: {
    searchInput,
    paginaTion,
  },
  name: "paramConfig",

  data() {
    return {
      visibility:false,
      limit,
      total: 0,
      offset: 0,
      parmeterTypelist: [],
      search:"",
      pweList:[],
      data_typeSel: [],
      form: {
        ...parameterKey,
        server_id:this.$route.query.server_id
      },
      parmeterv:"",
      tableData: [],
      model: {
        type: "add",
        visible: false,
      },
      resultVisable: false,
      ableList: [],
      unableList: [],
    };
  },
  methods: {
    back(n) {
      this.$router.go(n);
    },
    /**搜索 */
    searchChange(e) {
      this.search = e;
      this.offset = 0;
      this.getList();
    },
            
    batchExcel(e, fn) {
      let file = this.$refs[fn].files[0];
      let index = file.name.lastIndexOf(".")
      let suf = file.name.substr(index+1)
      const typeOk = ['xlsx'].includes(suf)
      if (typeOk) {
        readExcel(e, file, this[fn])
      }
      this.$refs[fn].value=''
    },

    /**分页 */
    getChangePage(val) {
      this.offset = val.offset;
      this.getList();
    },

    getSizePage(val) {
      this.offset = 0
      this.getList();
    },

    close() {
      this.model.visible = false;
      this.form = { ...parameterKey };
    },
    
    parmeterTypeChange() {
      this.form.pwe = ''
      this.pweList = []
      this.getParameterChoose()
    },
    /**提交 */
    submit() {
      this.$validator.validateAll().then((valid) => {
        if (valid) {
          this.addOrEdit();
        } else {
          this.$message.warning("有信息未填写正确");
        }
      })
    },
    /**删除 */
    doDelete(row) {
      this.id = row.id
      this.visibility = true
    },
    
    open(type, row = null) {
      this.$validator.reset()
      this.model.type = type
      if (row) {
        for (const k in parameterKey) {
          this.form[k] = row[k]
          this.form.server_id = row.server_id
        }
        this.id = row.id
        this.getParameterChoose()
      }
      this.model.visible = true
    },

    resultCancel() {
      this.resultVisable = false
      this.ableList = []
      this.unableList = []
    },
    
    resultSure() {
      this.confirm_import()
    },
    
    // 模板下载
    async exportData() {
      const res = await api.template(this).exportData()
      downLoadFile(res, `参数配置模板.xlsx`)
    },

            
    // 预导入
    async prepare_import(arr) {
      const { code, data_success, data_failed } = await api.template(this).prepare_import({
        server_id: this.$route.query.server_id,
        parameter: arr
      });
      if (code === 0) {
        this.ableList = data_success
        this.unableList = data_failed
        this.resultVisable = true
      }
    },
                
    // 实际导入
    async confirm_import() {
      const { code} = await api.template(this).confirm_import({
        server_id: this.$route.query.server_id,
        parameter: this.ableList
      });
      if (code === 0) {
        this.ableList = []
        this.unableList = []
        this.resultVisable = false
        this.getList()
      }
    },

    /**获取参数列表 */
    async getList() {
      const { code, data, total } = await api.template(this).getParameter({
        server_id: this.$route.query.server_id,
        offset: this.offset,
        limit: this.limit,
        name:this.search,
      })
      if(code === 0) {
        this.total = total
        this.tableData = data
      }
    },
    /**新增活编辑 */
    async addOrEdit() {
      let fn = this.model.type === 'add' ? 'addParameter' : 'updateParameter'
      const { code } = await api.template(this)[fn]({
        server_id: this.$route.query.server_id,
        ...this.form
      }, this.id)
      if (code === 0) {
        this.$message.success("操作成功");
        this.close();
        this.getList();
      }
    },
    /**删除参数 */
    async asyncDelete() {
      const { code } = await api.template(this).deleteParameter(this.id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.id = "";
        this.visibility = false;
        if (this.total % this.limit === 1) {
          if (this.offset >= this.limit) {
            this.offset -= this.limit;
          }
        }
        this.getList();
      }
    },
    /**获取参数类型 */
    async getParmeterType() {
      const { code, data } = await api.dropdown(this).downList({
        type: 'parmeter_type'
      })
      if (code === 0) {
        this.parmeterTypelist = data
      }
    },
    /**获取服务器参数 */
    async getParameterChoose () {
      const { code, data } = await api.template(this).getParameterChoose({
        server_id: this.$route.query.server_id,
        template_id: this.$route.query.id,
        type: this.form.parmeter_type
      })
      if(code === 0) {
        this.pweList = data || []
      }
    },

    async init() {
      await this.getParmeterType()
      await this.getList()
    }
  },
  created() {
    this.init()
  },
}
</script>

<style>
</style>